package com.ken.app.filters;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Liuk
 * @Mail: leo_work@aliyun.com
 * @Date: 2017/8/17 0017
 * @Desc: 设置跨域请求过滤器
 */
@Configuration
@ConfigurationProperties(prefix = "cors")
@Slf4j
public class FilerConfigation {

    private List<String> origins = new ArrayList<>();

    /**
     * 注入过滤器
     * @return
     */
    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        origins.forEach((origin) -> log.info("加载cors配置信息：[{}]", origin));
        origins.forEach((origin) -> config.addAllowedOrigin(origin));
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);

        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }
}
